package top.honlnk.czuan.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.honlnk.czuan.common.context.UserContextHolder;
import top.honlnk.czuan.common.exception.CustomException;
import top.honlnk.czuan.pojo.entity.User;
import top.honlnk.czuan.service.UserService;

/**
 * JWT拦截器
 */

@Slf4j
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        // 1. 获取请求头中的token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }
        // 2. 判断是否为空，或者非法
        if (StrUtil.isBlank(token)) {
            throw new CustomException("无token，请重新登录");
        }

        // 3. 获取token中的用户信息
        String userId;
        User user;
        try {
            userId = JWT.decode(token).getAudience().get(0);
            // 4. 根据用户id查询用户信息
            user = userService.getUserById(Integer.valueOf(userId));
        } catch (Exception e) {
            String errMsg = "非法token，请重新登录";
            log.error("{}，token={}", errMsg, token, e);
            throw new CustomException(errMsg);
        }
        if (user == null) {
            throw new CustomException("用户不存在，请重新登录");
        }
        // 5. 用户密码加签验证 token
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            jwtVerifier.verify(token);
        } catch (Exception e) {
            String errMsg = "token已过期，请重新登录";
            log.error("{}，token={}", errMsg, token, e);
            throw new CustomException(errMsg);
        }
        // 将用户信息保存到 ThreadLocal 中，方便后续方法获取用户信息
        UserContextHolder.setUser(user);
        return true;
    }
}